package com.xiaomage.sharedpreferences_contentprovider

import android.app.Application
import android.content.ContentValues
import android.content.Context
import android.net.Uri
import com.xiaomage.sharedpreferences_contentprovider.ConstantUtil.CONTENT_URI
import com.xiaomage.sharedpreferences_contentprovider.ConstantUtil.CURSOR_COLUMN_NAME
import com.xiaomage.sharedpreferences_contentprovider.ConstantUtil.CURSOR_COLUMN_TYPE
import com.xiaomage.sharedpreferences_contentprovider.ConstantUtil.CURSOR_COLUMN_VALUE
import com.xiaomage.sharedpreferences_contentprovider.ConstantUtil.NULL_STRING
import com.xiaomage.sharedpreferences_contentprovider.ConstantUtil.SEPARATOR
import com.xiaomage.sharedpreferences_contentprovider.ConstantUtil.TYPE_BOOLEAN
import com.xiaomage.sharedpreferences_contentprovider.ConstantUtil.TYPE_CLEAN
import com.xiaomage.sharedpreferences_contentprovider.ConstantUtil.TYPE_CONTAIN
import com.xiaomage.sharedpreferences_contentprovider.ConstantUtil.TYPE_FLOAT
import com.xiaomage.sharedpreferences_contentprovider.ConstantUtil.TYPE_GET_ALL
import com.xiaomage.sharedpreferences_contentprovider.ConstantUtil.TYPE_INT
import com.xiaomage.sharedpreferences_contentprovider.ConstantUtil.TYPE_LONG
import com.xiaomage.sharedpreferences_contentprovider.ConstantUtil.TYPE_STRING
import com.xiaomage.sharedpreferences_contentprovider.ConstantUtil.TYPE_STRING_SET
import com.xiaomage.sharedpreferences_contentprovider.ConstantUtil.VALUE
import java.util.HashMap

/**
 * Created by Administrator on 2018/4/1 0001.
 */
object SPHelper {
    val COMMA_REPLACEMENT = "__COMMA__"
    var context: Context? = null

    fun checkContext(){
        if(context==null){
            throw IllegalStateException("content has not benn initialed")
        }
    }
    fun init(application: Application){
        context=application.applicationContext
    }
    @Synchronized
    fun save(name:String?,t:Boolean){
        checkContext()
        //内容解析器
        val contentResolver= context?.contentResolver
        //"content://com.xiaomage.sharedpreferences_contentprovider/boolean/"+name
        val uri= Uri.parse(CONTENT_URI
                + SEPARATOR + TYPE_BOOLEAN + SEPARATOR + name)
        val contentValue=ContentValues()
        contentValue.put(VALUE,t)
        contentResolver?.update(uri,contentValue,null,null)
    }
    @Synchronized
    fun save(name:String?,t:String){
        checkContext()
        //内容解析器
        val contentResolver= context?.contentResolver
        //"content://com.xiaomage.sharedpreferences_contentprovider/string/"+name
        val uri= Uri.parse(CONTENT_URI
                + SEPARATOR + TYPE_STRING + SEPARATOR + name)
        val contentValue=ContentValues()
        contentValue.put(VALUE,t)
        contentResolver?.update(uri,contentValue,null,null)
    }

    @Synchronized
    fun save(name:String?,t:Int){
        checkContext()
        //内容解析器
        val contentResolver= context?.contentResolver
        //"content://com.xiaomage.sharedpreferences_contentprovider/int/"+name
        val uri= Uri.parse(CONTENT_URI
                + SEPARATOR + TYPE_INT+ SEPARATOR + name)
        val contentValue=ContentValues()
        contentValue.put(VALUE,t)
        contentResolver?.update(uri,contentValue,null,null)
    }
    @Synchronized
    fun save(name:String?,t:Long){
        checkContext()
        //内容解析器
        val contentResolver= context?.contentResolver
        //"content://com.xiaomage.sharedpreferences_contentprovider/long/"+name
        val uri= Uri.parse(CONTENT_URI
                + SEPARATOR + TYPE_LONG+ SEPARATOR + name)
        val contentValue=ContentValues()
        contentValue.put(VALUE,t)
        contentResolver?.update(uri,contentValue,null,null)
    }
    @Synchronized
    fun save(name:String?,t:Float){
        checkContext()
        //内容解析器
        val contentResolver= context?.contentResolver
        //"content://com.xiaomage.sharedpreferences_contentprovider/float/"+name
        val uri= Uri.parse(CONTENT_URI
                + SEPARATOR + TYPE_FLOAT + SEPARATOR + name)
        val contentValue=ContentValues()
        contentValue.put(VALUE,t)
        contentResolver?.update(uri,contentValue,null,null)
    }
    @Synchronized
    fun save(name:String?,ts:Set<String>){
        checkContext()
        //内容解析器
        val contentResolver= context?.contentResolver
        //"content://com.xiaomage.sharedpreferences_contentprovider/string_set/"+name
        val uri= Uri.parse(CONTENT_URI
                + SEPARATOR + TYPE_STRING_SET + SEPARATOR + name)
        val contentValue=ContentValues()
        val conver=HashSet<String>()
        for(t in ts){
            conver.add(t.replace(",",COMMA_REPLACEMENT))
        }
        contentValue.put(VALUE,conver.toString())
        contentResolver?.update(uri,contentValue,null,null)
    }

    fun getString(name: String?,defaultValue:String?):String?{
        checkContext()
        val contentResolver= context?.contentResolver
        //"content://com.xiaomage.sharedpreferences_contentprovider/string/"+name
        val uri=Uri.parse(CONTENT_URI + SEPARATOR + TYPE_STRING + SEPARATOR + name)
        val value=contentResolver?.getType(uri)
        if(value==null || value== NULL_STRING){
            return defaultValue
        }
        return value
    }

    fun getInt(name: String?,defaultValue:Int?):Int?{
        checkContext()
        val contentResolver= context?.contentResolver
        //"content://com.xiaomage.sharedpreferences_contentprovider/int/"+name
        val uri=Uri.parse(CONTENT_URI + SEPARATOR + TYPE_INT+ SEPARATOR + name)
        val value=contentResolver?.getType(uri)
        if(value==null || value== NULL_STRING){
            return defaultValue
        }
        return value as Int
    }

    fun getFloat(name: String?,defaultValue:Float?):Float?{
        checkContext()
        val contentResolver= context?.contentResolver
        //"content://com.xiaomage.sharedpreferences_contentprovider/float/"+name
        val uri=Uri.parse(CONTENT_URI + SEPARATOR + TYPE_FLOAT+ SEPARATOR + name)
        val value=contentResolver?.getType(uri)
        if(value==null || value== NULL_STRING){
            return defaultValue
        }
        return value as Float
    }

    fun getBoolean(name: String?,defaultValue:Boolean?):Boolean?{
        checkContext()
        val contentResolver= context?.contentResolver
        //"content://com.xiaomage.sharedpreferences_contentprovider/boolean/"+name
        val uri=Uri.parse(CONTENT_URI + SEPARATOR + TYPE_BOOLEAN+ SEPARATOR + name)
        val value=contentResolver?.getType(uri)
        if(value==null || value== NULL_STRING){
            return defaultValue
        }
        return value as Boolean
    }

    fun getLong(name: String?,defaultValue:Long?):Long?{
        checkContext()
        val contentResolver= context?.contentResolver
        //"content://com.xiaomage.sharedpreferences_contentprovider/long/"+name
        val uri=Uri.parse(CONTENT_URI + SEPARATOR + TYPE_LONG+ SEPARATOR + name)
        val value=contentResolver?.getType(uri)
        if(value==null || value== NULL_STRING){
            return defaultValue
        }
        return value as Long
    }
    fun getStringSet(name: String?,defaultValue:Set<String>?):Set<String>?{
        checkContext()
        val contentResolver= context?.contentResolver
        //"content://com.xiaomage.sharedpreferences_contentprovider/string_set/"+name
        val uri=Uri.parse(CONTENT_URI + SEPARATOR + TYPE_STRING_SET+ SEPARATOR + name)
        val value=contentResolver?.getType(uri)
        if(value==null || value== NULL_STRING || !value.matches("\\[.*\\]".toRegex())){
            return defaultValue
        }
        val sub=value.substring(1,value.length-1)
        val spl=sub.split(", ")
        val hasSet=HashSet<String>()
        for(s in spl){
            hasSet.add(s.replace(COMMA_REPLACEMENT,", "))
        }
        return hasSet
    }

    fun contains(name:String):Boolean{
        checkContext()
        val contentResolver= context?.contentResolver
        //"content://com.xiaomage.sharedpreferences_contentprovider/contain/"+name
        val uri=Uri.parse(CONTENT_URI + SEPARATOR + TYPE_CONTAIN+ SEPARATOR + name)
        val value=contentResolver?.getType(uri)
        if(value==null || value== NULL_STRING){
            return false
        }else{
            return value as Boolean
        }
    }

    fun remove(name: String?){
        checkContext()
        val contentResolver= context?.contentResolver
        //"content://com.xiaomage.sharedpreferences_contentprovider/long/"+name
        val uri=Uri.parse(CONTENT_URI + SEPARATOR + TYPE_LONG+ SEPARATOR + name)
        contentResolver?.delete(uri,null,null)
    }

    fun clear(){
        checkContext()
        val contentResolver= context?.contentResolver
        //"content://com.xiaomage.sharedpreferences_contentprovider/clean"
        val uri=Uri.parse(CONTENT_URI + SEPARATOR + TYPE_CLEAN)
        contentResolver?.delete(uri,null,null)
    }

    fun getAll(): Map<String, *> {
        checkContext()
        val cr = context?.getContentResolver()
        val uri = Uri.parse(CONTENT_URI + SEPARATOR + TYPE_GET_ALL)
        val cursor = cr?.query(uri, null, null, null, null)
        val resultMap = HashMap<String, Any?>()
        if (cursor != null && cursor.moveToFirst()) {
            val nameIndex = cursor.getColumnIndex(CURSOR_COLUMN_NAME)
            val typeIndex = cursor.getColumnIndex(CURSOR_COLUMN_TYPE)
            val valueIndex = cursor.getColumnIndex(CURSOR_COLUMN_VALUE)
            do {
                val key = cursor.getString(nameIndex)
                val type = cursor.getString(typeIndex)
                var value: Any? = null
                if (type.equals(TYPE_STRING, ignoreCase = true)) {
                    value = cursor.getString(valueIndex)
                    if ((value as String).contains(COMMA_REPLACEMENT)) {
                        val str = value as String?
                        if (str!!.matches("\\[.*\\]".toRegex())) {
                            val sub = str.substring(1, str.length - 1)
                            val spl = sub.split(", ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
                            val returns = java.util.HashSet<String>()
                            for (t in spl) {
                                returns.add(t.replace(COMMA_REPLACEMENT, ", "))
                            }
                            value = returns
                        }
                    }
                } else if (type.equals(TYPE_BOOLEAN, ignoreCase = true)) {
                    value = cursor.getString(valueIndex)
                } else if (type.equals(TYPE_INT, ignoreCase = true)) {
                    value = cursor.getInt(valueIndex)
                } else if (type.equals(TYPE_LONG, ignoreCase = true)) {
                    value = cursor.getLong(valueIndex)
                } else if (type.equals(TYPE_FLOAT, ignoreCase = true)) {
                    value = cursor.getFloat(valueIndex)
                } else if (type.equals(TYPE_STRING_SET, ignoreCase = true)) {
                    value = cursor.getString(valueIndex)
                }
                resultMap.put(key, value)
            } while (cursor.moveToNext())
            cursor.close()
        }
        return resultMap
    }
}